﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Odds.Entity;
using Odds.DBUtility;
using System.Data.SqlClient;
using System.Data;
using System.Data.Linq;

namespace Odds.DataAccess
{
    public class OddsIssueController
    {
        private string SQL_GETISSUEIDBYISSUENUMBER = "SELECT * FROM OddsIssue WHERE IssueRealID = @IssueRealID AND " +
                                                        SQL_CONDITION_UNDELETED;

        private const string SQL_CONDITION_UNDELETED = " IsDeleted = 0 ";
        private const string SQL_PARM_ISSUEREALID = "@IssueRealID";

        public Dictionary<string, Guid> Insert(OddsIssue oddsIssue)
        {
            Dictionary<string, Guid> result = new Dictionary<string,Guid>();
            try
            {
                Guid guid = Guid.NewGuid();
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat("EXEC Pro_OddsIssueInsert '{0}','{1}','{2}';",
                    guid, oddsIssue.IssueRealID, oddsIssue.EndDate.ToString());

                sql.AppendFormat(@"SELECT IssueRealID, IssueID FROM OddsIssue WHERE IssueRealID = {0}",
                    oddsIssue.IssueRealID);
                result = OddsSQLHelper.GetStringKeyDictionary(sql.ToString());
            }
            catch (Exception e)
            {
                throw e;
            }
            return result;
        }

        public OddsIssue GetOddsIssueByIssueID(Guid issueID)
        {
            OddsIssue result = new OddsIssue();

            using (OddsRecorderContextWrapper context = new OddsRecorderContextWrapper())
            {
                result = context.OddsIssues.Where(o => o.IssueID == issueID).FirstOrDefault();
            }
            return result;
        }
             
        public OddsIssue GetOddsIssueByIssueRealID(int issueRealID)
        {
            OddsIssue result = new OddsIssue();
            SqlParameter parm = new SqlParameter(SQL_PARM_ISSUEREALID, issueRealID);
            
            result = OddsSQLEntityHelper<OddsIssue>.GetEntity(SQL_GETISSUEIDBYISSUENUMBER, parm);
            return result;
        }

        public List<OddsIssue> GetAllOddsIssue()
        {
            List<OddsIssue> result = new List<OddsIssue>();
            using (OddsRecorderContextWrapper context = new OddsRecorderContextWrapper())
            {
                result = context.OddsIssues.Where(o => o.IsDeleted == false).OrderByDescending(o => o.IssueRealID).ToList();
            }
            return result;
        }

        public int GetLastIssueRealNumber()
        {
            int result = 0;
            string sql = "SELECT TOP 1 IssueRealID FROM OddsIssue ORDER BY IssueRealID DESC";
            int.TryParse(OddsSQLHelper.ExecuteScalar(sql, null).ToString(), out result);
            return result;            
        }
    }
}
